--
-- Author: shunguo.chen
-- Date: 2018-06-01 11:15:58
--
-- UIController 游戏通用界面控制器，一般通用界面的逻辑应该在这里处理
-- 缓解UIHandler压力，UIHandler只做中转功能
--

local RollNoticeView = import("..views.RollNoticeView")
local ItemGetActView = import("..views.ItemGetActView")
local QuickUseView = import("..views.QuickUseView")
local ThirdLevelTipsPanel = require("app.newFloatTips.ThirdLevelTipsPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("WorldModel")

    -- 快捷装备／使用
    self._quickUseView = nil
    self._quickUseItems = {}
    -- 是否在快捷请求中，true不通过UD的operation触发下一个快捷使用数据
    self._isInQuickUse = false
    -- 是否在快捷使用的延迟
    self._quickUseCron = nil

    -- handler
    self._equipHandler = UD:onChanged("equip",handler(self, self.updateEquip))
    self._formulaHandler = UD:onChanged("formulaId",handler(self, self.updateFormula))
    self._bagHandler = UD.bag:onChanged(handler(self, self.updateBag))
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)

    UD:unChanged("equip", self._equipHandler)
    UD:unChanged("formulaId", self._formulaHandler)
    UD.bag:unChanged(self._bagHandler)
end

function ClassRef:listEvent()
    return {
        "onMapChanged"
    }
end

function ClassRef:onEvent(eventName, data)
    if eventName == "onMapChanged" then
        self:clearQuickView()
        if data then
            self._model:C2S_RecoveryGameInfo()
        end
    end
end

-- 显示滚动提示／走马灯
function ClassRef:showRollNotice(notices)
    local viewName = RollNoticeView:getViewName()
    local view = UIHandler:getChildFromUiParent(viewName)
    if not view then
        view = RollNoticeView.new(app.mvc.VIEWTYPE_NORMAL)
        UIHandler:addChildToUiParent(view, SceneZOrder.rollNoticeZOrder, viewName)
    end
    view:addNotice(notices)
    view:show()
end
-- 隐藏滚动提示／走马灯
function ClassRef:hideRollNotice()
    local viewName = RollNoticeView:getViewName()
    local view = UIHandler:getChildFromUiParent(viewName)
    if view then
        view:hide()
    end
end

-- 右下角获得物品动画
-- data = {item=Item/Equip/Jewel/MountSoul/Daibi, num=5}
function ClassRef:addGetItemView(data)
    local viewName = ItemGetActView.__cname
    local view = UIHandler:getChildFromUiParent(viewName)
    if not view then
        view = ItemGetActView.new(app.mvc.VIEWTYPE_NORMAL)
        UIHandler:addChildToUiParent(view, SceneZOrder.itemGetZOrder, viewName)
    end
    view:setVisible(true)
    view:addItem(data)
end

-- 清空右下角获得物品动画
function ClassRef:clearGetItemView()
    local view = UIHandler:getChildFromUiParent(ItemGetActView.__cname)
    if view then
        view:clearItems()
    end
end

-- 资源获取飘字
function ClassRef:pushGetInfoToasts(info)
    if DEBUG == -1 then return end
    -- 没有num，或者nun=0就不飘字了
    if info and info.num then
        local message = nil
        if info.name == "item" then
            message = GD:getMessageStr("getitem")
            message = string.format(message, info.showName or "", info.num)
        elseif info.name == "coin" then
            message = GD:getMessageStr("getcoin")
            message = string.format(message, info.num)
        elseif info.name == "gold" then
            message = GD:getMessageStr("getgold")
            message = string.format(message, info.num)
        elseif info.name == "exp" then
            message = GD:getMessageStr("getexp")
            message = string.format(message, info.num)
        elseif info.name == "fame" then
            message = GD:getMessageStr("getfame")
            message = string.format(message, info.num, info.showName or "")
        elseif info.name == "power" then
            message = GD:getMessageStr("costpower")
            message = string.format(message, info.num)
        elseif info.name == "combatPower" then
            message = string.format(L("lua_code_text_527") .. " %+d", info.num)
        end
        if message then
            display.pushToast(message)
        end
    end
end

-- 主界面右上角提示
-- data = {
--     remindId = ,
--     params =,
-- }
function ClassRef:showThirdLevelTips(data)
    local conf = GD:getRemindConfById( data.remindId )
    if conf.type ~= "1" then return end

    local view = UIHandler:getPopupUiByKey("ThirdLevelTipsPanel")
    if not view then
        view = ThirdLevelTipsPanel.create()
        view:setPosition(display.width, display.height)
        UIHandler:addPopupUi(view, "ThirdLevelTipsPanel", true)
    end

    view:setLocalZOrder(9999)
    view:addData(data)
end

------------------------------------ QuickUseView start ------------------------------------
function ClassRef:isQuickUseViewVisible()
    return self._quickUseView and self._quickUseView:isVisible()
end
function ClassRef:_isQuickUseViewHasData()
    return self._quickUseView and self._quickUseView:getData() ~= nil
end
function ClassRef:showQuickView(ignoreDispatch)
    if self:_isQuickUseViewHasData() and not self:isQuickUseViewVisible() then
        self._quickUseView:show(ignoreDispatch)
    end
end
function ClassRef:hideQuickView(ignoreDispatch)
    if self:isQuickUseViewVisible() then
        self._quickUseView:hide(true, ignoreDispatch)
    end
end
function ClassRef:clearQuickView()
    if self:_isQuickUseViewHasData() then
        self._quickUseView:hide()
    end

    self._quickUseItems = {}
    if self._quickUseCron then
        scheduler.cancelCron(self._quickUseCron)
        self._quickUseCron = nil
    end
end
function ClassRef:quickViewCheckGuide()
    if self:isQuickUseViewVisible() then
        self._quickUseView:checkGuide()
    end
end
-- 下一个快捷使用
function ClassRef:_nextQuickUseView()
    local view = self._quickUseView
    if not view then
        view = QuickUseView.new(app.mvc.VIEWTYPE_NORMAL)
        UIHandler:addChildToUiParent(view, SceneZOrder.chatUiZOrder, view:getViewName())
        view:onClearView(function() 
            self._quickUseView = nil 
        end)
        view:onOperate(function(op, data)
            if op == "close" then
                self:_nextQuickUseView()
            elseif op == "visibleChange" then
                -- 有快捷界面时需要隐藏主界面右下角提示
                UIHandler:setDesktopTipVisible(not data)
            elseif op == "useItem" then
                if data.itemBagType == Enums.ItemBagType.equip then
                    self._isInQuickUse = true

                    local function reqEquip()
                        app:sendMsg("NewBagModel", "confirmReqEquipEquipmentX", data,
                            function(isOk)
                                self._isInQuickUse = false
                                self:_nextQuickUseView()
                            end)
                    end
                    if data:needBindTip() then
                        local confirmDialog = display.newConfirmDialog(GD:getMessageStr("bounditem"),
                                reqEquip,
                                function()
                                    self._isInQuickUse = false
                                    self:_nextQuickUseView()
                                end)

                        confirmDialog:setConfirmText(L("tips_ok"))
                        confirmDialog:setCancelText(L("tips_cancel"))
                        UIHandler:addPopDialog(confirmDialog)
                    else
                        reqEquip()
                    end
                else
                    -- item
                    local tp = data:getItemType()
                    if tp == Enums.ItemType.partnerExp then
                        -- 随从药水，打开随从界面
                        UIHandler:handleMessage({id=Constant.FUNC_TYPE_MERCENARY, mode="open"})
                        self:_nextQuickUseView()
                    elseif data:isAssociateBox() then -- 关联的道具
		                app:sendMsg("SummonBossController", "openBoxView", data)
                        self:_nextQuickUseView()
                    else
                        self._isInQuickUse = true
                        app:sendMsg("NewBagModel", "reqUseItem", data.uid, data.tid, 1, 
                            function(isOk)
                                self._isInQuickUse = false
                                self:_nextQuickUseView()
                            end)
                    end
                end
            end
        end)
        view:hide()
        self._quickUseView = view
    end

    local nextItem, item
    while #self._quickUseItems > 0 do
        item = table.remove(self._quickUseItems, 1)
        -- 检测是否还存在这个道具，可能会被使用掉
        if self:_isQuickUse(item) then
            nextItem = item
            break
        end
    end

    if nextItem then
        view:refresh(nextItem)

        if view:isVisible() then return end
        -- 主界面引导中暂时不显示，等引导结束会显示
        if app:sendMsg("GuideController", "isInDesktopGuide") then return end
        if StoryManager:isEnterStoryMode() then return end

        view:show()
    else
        -- 没有了，隐藏
        view:hide()
    end
end

function ClassRef:_isQuickUse(item)
    local itemData = UD:getItem( item.uid )
    if itemData then
        if itemData.itemBagType == Enums.ItemBagType.equip then --新装备提醒
            -- 1.可以装备 2.比当前装备好
            if itemData:isCanEquip() and itemData:isBetterThanEquipOnPlayer() then
                return true
            end
        elseif itemData.itemBagType == Enums.ItemBagType.item then
            -- 1.可以使用 2.可以快捷使用
            if itemData:isCanUse() and itemData:isQuickUse() then
                local itemType = itemData:getItemType()
                if itemType == Enums.ItemType.paper then
                    -- 配方
                    local dropLoot = itemData:getDropLoot()
                    return UD:isFormulaCanStudy(dropLoot.id)
                elseif itemType == Enums.ItemType.mountSummon then
                    -- 缰绳坐骑
                    local dropLoot = itemData:getDropLoot()
                    return UD:getMountByID(dropLoot.id) == nil
                elseif itemType == Enums.ItemType.rune then
                    -- 符文
                    local dropLoot = itemData:getDropLoot()
                    return not UD:isRuneGot(dropLoot.id)
                elseif itemType == Enums.ItemType.partnerSummon then
                    -- 随从契约
                    local dropLoot = itemData:getDropLoot()
                    return not UD.partnersData:isPartnerHaveById(dropLoot.id)
                elseif itemType == Enums.ItemType.lifeSkill then
                    -- 生活技能书
                    local dropLoot = itemData:getDropLoot()
                    return UD:getLifeSkillById(dropLoot.id) == nil
                elseif itemType == Enums.ItemType.enegy then
                    -- 体力药水
                    return not UD:isPowerFull()
                elseif itemType == Enums.ItemType.ship then
                    -- 船长室收藏品
                    local dropLoot = itemData:getDropLoot()
                    return not app:sendMsg("CaptainController", "hasCollector", dropLoot.id)
                end
                return true
            end
        end
    end
    return false
end

-- 检测快捷使用道具／装备
function ClassRef:checkQuickUse(item)
    if not UIHandler:isFunctionOpen(Constant.FUNC_TYPE_QUICK_USE) then
        return
    end

    -- 竞速副本不能快进使用，会刷新角色形象
    if DungeonManager:isRace() then return end

    if self:_isQuickUse(item) then
        table.insert(self._quickUseItems, item)

        if self:_isQuickUseViewHasData() then return end
        if self._quickUseCron then return end

        local delay = 0.2
        local id = item:getId()
        if id and (id == 7110083 or id == 7210083 or id == 7410083 or id == 7510083) then
            -- TODO 暂时这几个道具延迟5秒，为了适配引导
            delay = 5
        end

        -- print("checkQuickUse id delay", id, delay)

        -- 快捷装备延迟1秒出现
        self._quickUseCron = scheduler.newCron(function()
            self._quickUseCron = nil
            self:_nextQuickUseView()
        end, delay)
    end
end
------------------------------------ QuickUseView end ------------------------------------


-------------------------------------------------------
function ClassRef:updateEquip(uid,equip,opt)
    if opt == "insert" then
        -- 1.快捷操作界面有数据 2.当前操作的是装备 3.和更改是同一位置的装备 4.比穿的装备更差了
        if not self._isInQuickUse and self:_isQuickUseViewHasData() then
            local curData = self._quickUseView:getData()
            if curData.itemBagType == Enums.ItemBagType.equip
                and curData:isPosCanReplace(equip:getPos())
                and not curData:isBetterThanEquipOnPlayer() then

                self:_nextQuickUseView()
            end
        end
    end
end

function ClassRef:updateBag(uid,item,amountGot,opt)
    if opt == "delete" then
        -- 1.快捷操作界面有数据 2.当前操作的和删除的是同一物品
        if not self._isInQuickUse and self:_isQuickUseViewHasData() then
            local curData = self._quickUseView:getData()
            if curData.uid == uid then
                self:_nextQuickUseView()
            end
        end
    end
end

-- 配方变化
-- formulaId FormulaId结构
function ClassRef:updateFormula(id, formulaId)
    -- 1.快捷操作界面有数据 2.当前操作的和删除的是同一物品
    if not self._isInQuickUse and self:_isQuickUseViewHasData() then
        local curData = self._quickUseView:getData()
        if curData.itemBagType == Enums.ItemBagType.item
            and curData:getItemType() == Enums.ItemType.paper
            and tonumber(curData:getUseValue()) == id then
            self:_nextQuickUseView()
        end
    end
end

-------------------------------------------------------
function ClassRef:onOperate(op, data)
    -- print("UIController:onOperate op", op)
    if op == "" then

    end
end

return ClassRef
